package com.eqdd.yiqidian.ui.select;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;

import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.SelectTextMultiActivityCustom;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.rebuild.OptionBean;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.eqdd.yiqidian.widget.FlowLayoutManager;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.model.Response;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Flowable;
import io.reactivex.functions.Function;

/**
 * @author吕志豪 .
 * @date 17-12-6  上午9:54.
 * Github :https://github.com/lvzhihao100
 * E-Mail：1030753080@qq.com
 * 简书 :http://www.jianshu.com/u/6e525b929aac
 */

public class SelectTextMultiActivity extends BaseActivity {

    private SelectTextMultiActivityCustom dataBinding;
    private List<String> strings;
    private SlimAdapterEx slimAdapterEx;
    private int deep;
    private int maxNum;
    private int option;

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_select_text_multi);
        initTopTitleBar(View.VISIBLE, "选择");
        initTopRightText("确定", v -> {
            if (slimAdapterEx.getData().get(0) instanceof String) {
                ArrayList<String> strResults = new ArrayList<>();
                Flowable.fromIterable(slimAdapterEx.getData())
                        .filter(o -> o instanceof String)
                        .subscribe(o -> strResults.add((String) o));
                Intent intent = new Intent();
                intent.putStringArrayListExtra(Config.STRING_LIST,strResults);
                setResult(Config.SUCCESS, intent);
                finish();
            } else {
                ToastUtil.showShort("至少选一个");
            }
        });
    }

    @Override
    public void initData() {
        maxNum = getIntent().getIntExtra(Config.MAX_NUM, Integer.MAX_VALUE);
        option = getIntent().getIntExtra(Config.OPTION, 0);
        deep = getIntent().getIntExtra(Config.DEEP, 1);
        loadData();

    }

    private void loadData() {
        OkGo.<List<OptionBean>>get(HttpConfig.BASE_URL + HttpConfig.AREA_OPTIONS)
                .params("type", option)
                .cacheMode(CacheMode.IF_NONE_CACHE_REQUEST)
                .cacheKey(HttpConfig.BASE_URL + HttpConfig.AREA_OPTIONS + option)
                .execute(new DialogCallBack<List<OptionBean>>(SelectTextMultiActivity.this) {
                    @Override
                    public void onSuccess(Response<List<OptionBean>> response) {
                        List<OptionBean> optionBean = response.body();
                        dealData(optionBean);
                    }

                    @Override
                    public void onCacheSuccess(Response<List<OptionBean>> response) {
                        super.onCacheSuccess(response);
                        List<OptionBean> optionBean = response.body();
                        dealData(optionBean);
                    }

                    @Override
                    public void onError(Response<List<OptionBean>> response) {
                        super.onError(response);
                        ToastUtil.showShort("数据获取失败，请稍候重试");
                    }
                });
    }

    private void dealData(List<OptionBean> optionBean) {
        strings = new ArrayList<>();
        switch (deep) {
            case 1://获取一级目录所有条目
                Flowable.fromIterable(optionBean)
                        .subscribe(bean -> strings.add(bean.getName()));
                break;
            case 2://获取二级目录所有条目
                Flowable.fromIterable(optionBean)
                        .flatMap(optionBean12 -> Flowable.fromIterable(optionBean12.getSub()))
                        .subscribe(optionBean1 -> strings.add(optionBean1.getName()));
                break;
            case 3://获取三级目录所有条目
                Flowable.fromIterable(optionBean)
                        .flatMap(optionBean12 -> Flowable.fromIterable(optionBean12.getSub()))
                        .flatMap(optionBean123 -> Flowable.fromIterable(optionBean123.getSub()))
                        .subscribe(optionBean1234 -> strings.add(optionBean1234.getName()),System.out::print);
                break;
        }
        initText();


    }

    private void initText() {
        dataBinding.recyclerView.setLayoutManager(new FlowLayoutManager());
        slimAdapterEx = SlimAdapterEx.create().register(R.layout.list_item_74, new SlimInjector<String>() {
            @Override
            public void onInject(String data, IViewInjector injector) {
                injector.text(R.id.tv_content, data)
                        .clicked(R.id.ll_root, v -> {
                            int index = slimAdapterEx.getData().indexOf(data);
                            slimAdapterEx.getData().remove(index);
                            slimAdapterEx.notifyItemRemoved(index);
                            if (slimAdapterEx.getData().size() == maxNum-1) {
                                slimAdapterEx.getData().add(1);
                            }
                        });
            }
        })
                .register(R.layout.list_item_75, new SlimInjector<Integer>() {
                    @Override
                    public void onInject(Integer data, IViewInjector injector) {
                        injector.with(R.id.autoTextView, view -> {
                            AutoCompleteTextView autoCompleteTextView = (AutoCompleteTextView) view;
                            ArrayAdapter arrayAdapter = new ArrayAdapter(SelectTextMultiActivity.this, R.layout.support_simple_spinner_dropdown_item, strings);
                            //设置适配
                            autoCompleteTextView.setAdapter(arrayAdapter);
                            autoCompleteTextView.setOnItemClickListener((parent, view1, position, id) -> {
                                String tag = (String) parent.getAdapter().getItem(position);
                                slimAdapterEx.getData().add(slimAdapterEx.getData().size() - 1, tag);
                                slimAdapterEx.notifyItemInserted(slimAdapterEx.getData().size() - 2);
                                autoCompleteTextView.setText("");
                                if (slimAdapterEx.getData().size() == maxNum+1) {
                                    slimAdapterEx.getData().remove(maxNum);
                                    slimAdapterEx.notifyItemRemoved(maxNum);
                                }
                            });
                            autoCompleteTextView.setThreshold(0);
                        });
                    }
                }).attachTo(dataBinding.recyclerView).updateData(new ArrayList());
        slimAdapterEx.getData().add(1);
        slimAdapterEx.notifyItemInserted(0);
    }
    @Override
    public void setView() {


    }
}
